<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Controllers\Api\Device\JiejieApi;
use App\Models\XcDevice;
use App\Models\XcSite;
use App\Http\Controllers\Api\WechatController;
use Illuminate\Support\Facades\DB;

/**
 * 站点管理控制层
 *
 */
class SiteController extends Controller
{

    /**
     * 站点列表数据，可通过经纬度，或者区域查询
     * 
     * 
     * @return \Illuminate\Http\JsonResponse
     */ 
    public function list(Request $request)
    {
        $res = ['code' => -1,'msg' => 'failed'];
        $longitude = $request->get("longitude", "");
        $latitude  = $request->get("latitude", "");
        $city_code  = $request->get("city_code", "");
        $region_code  = $request->get("region_code", "");

        $site_ids = XcDevice::where([['site_id', '>', 0],['renter_id', '>',0]])->pluck("site_id")->toArray();

        $site = XcSite::whereIn('id', $site_ids);
        if (!empty($city_code)) $site = $site->where("city_code", $city_code);
        if (!empty($region_code)) $site = $site->where("region_code", $region_code);

        if ($longitude > 0 && $latitude > 0 )
        {
            //下面只用到了field，计算字段里面的经纬度和传递过来经纬度的距离，目前先保留两个，取绝于后需实际应用中是否要排序
            $distance = "ACOS(SIN(( $latitude * 3.1415) / 180 ) *SIN((latitude * 3.1415) / 180 ) +COS(( $latitude* 3.1415) / 180 ) * COS((latitude * 3.1415) / 180 ) *COS(( $longitude* 3.1415) / 180 - (longitude * 3.1415) / 180 ) ) * 6380";
            $field = "ROUND(6370.996 * 2 * ASIN(SQRT(POW(SIN(($latitude*3.1415/180 - latitude*3.1415/180)/2),2) + COS($latitude*3.1415/180)*COS(latitude*3.1415/180) * POW(SIN(($longitude*3.1415/180 - longitude*3.1415/180)/2),2))) * 1000) AS mi";
            $site = $site->select('*')->addSelect(\DB::raw($distance . ' as distance'))->addSelect(\DB::raw($field))->orderBy('mi', 'ASC');
        }
        $site = $site->with(['device','washmode']);
        $site = $site->paginate($request->get('limit',20));

        $res = [
            'code' => 0,
            'msg'   => 'success',
            'count' => $site->total(),
            'data'  => $site->items()
        ];

        return response()->json($res);
    }

    /**
     * 单个站点数据，指定站点洗车模式的列表等
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail(Request $request)
    {
        $res = ['code' => -1,'msg' => 'failed'];
        $openid     = $request->get("openid");//微信用户ID 
        $site_id    = $request->get("site_id");//指定的站点ID
        $site       = XcSite::where("id", $site_id)->with(['renter','device','washmode'])->first();

        $res['code'] = 0;
        $res['msg']  = "success";
        $res['data'] = $site;

        return response()->json($res);
    }


    /**
     * 推荐单个站点的信息
     * 
     */ 
    public function recommend(Request $request)
    {   
        $res = ['code' => -1,'msg' => 'failed'];
        $longitude = $request->get("longitude", "");
        $latitude  = $request->get("latitude", "");
        $city_code  = $request->get("city_code", "");
        $region_code  = $request->get("region_code", "");

        $site_ids = XcDevice::where([['site_id', '>', 0],['renter_id', '>',0]])->pluck("site_id")->toArray();

        $site = XcSite::where("status", 0)->whereIn('id', $site_ids);
        if (!empty($city_code)) $site = $site->where("city_code", $city_code);
        if (!empty($region_code)) $site = $site->where("region_code", $region_code);

        if ($longitude > 0 && $latitude > 0 )
        {
            //下面只用到了field，计算字段里面的经纬度和传递过来经纬度的距离，目前先保留两个，取绝于后需实际应用中是否要排序
            $distance = "ACOS(SIN(( $latitude * 3.1415) / 180 ) *SIN((latitude * 3.1415) / 180 ) +COS(( $latitude* 3.1415) / 180 ) * COS((latitude * 3.1415) / 180 ) *COS(( $longitude* 3.1415) / 180 - (longitude * 3.1415) / 180 ) ) * 6380";
            $field = "ROUND(6370.996 * 2 * ASIN(SQRT(POW(SIN(($latitude*3.1415/180 - latitude*3.1415/180)/2),2) + COS($latitude*3.1415/180)*COS(latitude*3.1415/180) * POW(SIN(($longitude*3.1415/180 - longitude*3.1415/180)/2),2))) * 1000) AS mi";
            $site = $site->select('*')->addSelect(\DB::raw($distance . ' as distance'))->addSelect(\DB::raw($field))->orderBy('mi', 'ASC');
        }
        $site = $site->with(['device','washmode' => function($q){
                    $q->with("factorywashmode");
                }]);
        $site = $site->limit(1)->get();

        $res = [
            'code' => 0,
            'msg'   => 'success',
            'data'  => $site
        ];


        return response()->json($res);
    }

    /**
     * 管理端-所有设备的列表
     * 
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */ 
    public function sitedevicelist(Request $request)
    {
        $res = ['code' => -1,'msg' => 'failed'];
        $status_arra = [0 => '营业中',
                        1 => '机器故障关闭',
                        2 => '天气原因关闭'
                         ];
        $name = $request->get("name", "");
        $siteids = [];
        if (!empty($name)){
            $siteids = XcSite::where([['name', 'like','%'.$name.'%']])->get()->pluck("id")->toArray();
        } 
        //DB::connection()->enableQueryLog();#开启执行日志
        $device = XcDevice::where("status", 0);
        if (!empty($name)){
            $device = $device->whereIn('site_id', $siteids)->with(["site"])->paginate($request->get('limit',20));
        }else{
            $device = $device->with(["site"])->paginate($request->get('limit',20));
        }
        //print_r(DB::getQueryLog());exit;
        $res['code'] = 0;
        $res['msg']  = 'success';
        $res['data'] = ['devicelist' => $device, 'status_arra' => $status_arra];
        return response()->json($res);
    }

    /**
     * 更新站点状态，分所有站点和单个站点
     * 
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */ 
    public function sitemanage(Request $request)
    {
        $res = ['code' => -1,'msg' => 'failed'];
        $status_arra = [0 => ['status' => 0, 'msg' => '营业中'],
                        1 => ['status' => 1, 'msg' => '机器故障关闭'],
                        2 => ['status' => 1, 'msg' => '天气原因关闭']
                         ];

        $city_code = $request->get("city_code", '420100');
        $site_id = $request->get("site_id", 0);
        $index   = $request->get("index",0);

        $status = $status_arra[$index]['status'];
        $msg    = $status_arra[$index]['msg'];
        //更新单个站点状态
        if ($site_id > 0)
        {
            $flag = XcSite::where("id", $site_id)->update(['status' => $status, 'msg' => $msg]);
        //更新所有指定城市的站点状态
        }else{
            $flag = XcSite::where('city_code', $city_code)->update(['status' => $status, 'msg' => $msg]);;
        }

        $res['code'] = 0;
        $res['msg']  = 'success';
        $res['data'] = $flag;

        return response()->json($res);
    }











}